import fileUtil from "./fileUtil";
import { getFileSuffix, BasePath } from "./fileUtil";
import { showToast } from "./util";


export type LocalFileType = "image" | "video";
export type FileType = "voice" | "music" | LocalFileType;
export type MessageFileType = LocalFileType | "audio";


interface TempFile {
	path: string
	customName: string
	originalName: string
}

const IMAGE_PATH = "/images" as const;
const VOICE_PATH = "/voices" as const;
const MUSIC_PATH = "/musics" as const;
const VIDEO_PATH = "/videos" as const;

const PathMap: Record<FileType, string> = {
	"voice": VOICE_PATH,
	"music": MUSIC_PATH,
	"video": VIDEO_PATH,
	"image": IMAGE_PATH,
}

const AllowedAudioType = ["mp3", "wav", "aac", "ac3", "wma", "ogg", "m4a", "flac", "opus", "ape", "amr"];

const FileCount = 1;
export type ChooseType = "wxchat" | "local";

const ChooseMessageOptions: Record<MessageFileType, UniApp.ChooseMessageFileOption> = {
	"image": {
		count: FileCount,
		type: "image",
	},
	"audio": {
		count: FileCount,
		type: "file",
		extension: AllowedAudioType,
	},
	"video": {
		count: FileCount,
		type: "video",
	}
}


const fileManager = {
	/**
	 * 从客户端会话选择文件
	 * @param {MessageFileType} type 文件类型, 支持图片、音频、视频
	 * @param {number} count 最多可以选择的文件个数，可以 0～100
	 * @return {Promise<UniApp.ChooseFile[]>} 选择的文件列表，包含path, size, name, type
	 */
	chooseMessageFile(type: MessageFileType, count?: number): Promise<UniApp.ChooseFile[]> {
		let c = count || FileCount;
		return new Promise((resolve, reject) => {
			uni.chooseMessageFile({
				...ChooseMessageOptions[type],
				count: c,
				success(res) {
					resolve(res.tempFiles);
				},
				fail(err) {
					resolve([]);
				}
			})
		})
	},
	
	/**
	 * 从手机相册中选择图片或视频
	 * @param {LocalFileType} type 文件类型, 支持图片、视频
	 * @param {number} count 最多可以选择的文件个数，最多可支持20个文件 
	 * @return {Promise<UniApp.MediaFile[]>} 选择的文件列表, 包含tempFilePath, size, fileType
	 */
	chooseLocalFile(type: LocalFileType, count?: number): Promise<UniApp.MediaFile[]> {
		return new Promise((resolve, reject) => {
			let c = count || FileCount;
			uni.chooseMedia({
				count: c,
				mediaType: [type],
				sourceType: ["album"],
				success(res) {
					resolve(res.tempFiles);
				},
				fail(res) {
					resolve([]);
				}
			})
		})
	},
	
	getFileList(type: FileType): string[] {
		const path = PathMap[type];
		return fileUtil.readdirSync(path);
	},
	
	saveFile(type: FileType, tempFile: TempFile): string {
		const basePath = PathMap[type];
		// 检查目录并创建目录
		if (!fileUtil.hasFileOrDirSync(basePath)) {
			fileUtil.mkdirSync(basePath);
		}
		let name = tempFile.customName;
		if (name === "") {
			name = getFileNameFromTempFile(tempFile.originalName);
		}
		const suffix = getFileSuffix(tempFile.path);
		const tempFilePath = tempFile.path;
		const filePath = `${basePath}/${name}_${Date.now()}${suffix}`;
		return fileUtil.saveFileSync(tempFilePath, filePath);
	},
	
	saveFiles(type: FileType, tempFileList: TempFile[]): string[] {
		const result: string[] = [];
		tempFileList.forEach((item) => {
			const res = this.saveFile(type, item);
			result.push(res);
		})
		return result;
	},
	
	deleteFile(type: FileType, filename: string): Promise<boolean> {
		const path = PathMap[type];
		const name = removeTimestampFromFilename(filename);
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: "确认删除",
				content: `确认删除${name}吗?`
			}).then(res => {
				if (res.confirm) {
					// 用户确认
					const result = fileUtil.deleteFileSync(`${path}/${filename}`);
					result ? showToast("删除", "success") : showToast("删除", "error");
					resolve(result);
				} else if (res.cancel) {
					resolve(false);
				}
			})
		})
	},
	
	hasDir(type: FileType): boolean {
		const path = PathMap[type];
		return fileUtil.hasFileOrDirSync(path);
	},
	
	mkdir(type: FileType): boolean {
		const path = PathMap[type];
		
		return fileUtil.mkdirSync(path);
	},
	
	async getSavedFileList(): Promise<string[]> {
		const res = await fileUtil.getSavedFileList();
		return res.map(item => item.filePath);
	},
	
	getFullPath(type: FileType, path: string): string {
		const p = PathMap[type];
		return `${BasePath}${p}/${path}`;
	}
}

/**
 * 获取文件的文件名
 * @param {string} path 文件路径
 * @return 文件名
 */ 
export function getFileName(path: string): string {
	const src = removeTimestampFromFilename(path);
	const i = src.lastIndexOf("/");
	const j = src.lastIndexOf(".");
	return src.slice(i + 1, j);
}

/**
 * 获取临时文件的文件名
 * @param {string} name 路径路径 
 * @return 不带后缀的文件名
 */ 
export function getFileNameFromTempFile(name: string): string {
	return name.split(".")[0];
}

/**
 * 获取文件名中的时间戳
 * @param {string} filename 文件名 
 * @return 时间戳
 */ 
export function getTimestampFromFilename(filename: string): string {
	const lastPointIdx = filename.lastIndexOf(".");
	return filename.slice(lastPointIdx - 13, lastPointIdx);
}
/**
 * 移除文件名中的时间戳（例如：_1752928451076）
 * @param filename 原始文件名
 * @returns 去除时间戳后的文件名
 */
export function removeTimestampFromFilename(filename: string): string {
	return filename.replace(/_\d{13}(?=\.\w+$)/, '');
}


export default fileManager;